package DEEPERsource.DEEPERsource.source.client;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.List;

import machinelearning.features.FeatureBuilder;
import machinelearning.kernel.KimKernel;
import machinelearning.kernel.Kernel;
import machinelearning.kernel.SyntacticKernel;
import machinelearning.utils.PrecomputedKernel;
import machinelearning.wekawrapper.Dataset;
import parser.Parser;
import parser.StanfordParser;
import preprocessing.SimplePreprocessor;
import corpus.Text;
import corpus.ppi.CorpusFactory;
import deeper.Interaction;

public class AIMedKernelBuilder {
	
	/**
	 * 
	 * @param args
	 * -xml path_to_xml
	 * -serialized path_to_serialized_data (opt)
	 * -output output_dir 
	 * -folds num_folds
	 * -kernelType syntactic|dependency
	 */
	public static void main(String[] params){
		String sourceXML = "", serialDir = "", out = "", kernelType = "";
		int numFolds = 0;
		for(int i = 0; i< params.length; i++){
			if(params[i].equals("-xml")){
				sourceXML = params[++i];
			}
			if(params[i].equals("-serialized")){
				serialDir = params[++i];
			}
			if(params[i].equals("-output")){
				out = params[++i];
			}
			if(params[i].equals("-folds")){
				numFolds = Integer.parseInt(params[++i]);
			}
			if(params[i].equals("-kernelType")){
				kernelType = params[++i];
			}
		}
		CorpusFactory cFactory = new CorpusFactory();
		Text corpus = cFactory.getCorpusFromPPIXML(sourceXML, new SimplePreprocessor());
		if(!serialDir.equals("")){
			corpus.parse(null,"serialized",serialDir);
		}else{
			Parser stanfordParser = new StanfordParser();
			stanfordParser.init("-maxLength","70","-dependencyType","typedDependenciesCCprocessed");
			corpus.parse(stanfordParser);
		}
		Dataset data = new Dataset(corpus.interactions(), (FeatureBuilder)null);
		Kernel k = null;
		if(kernelType.equals("syntactic")){
			k = new SyntacticKernel();
		}else if(kernelType.equals("dependency")){
			k = new KimKernel();
		}
		PrecomputedKernel kernel = new PrecomputedKernel(corpus.interactions(), k);
		for(int i = 0; i<numFolds; i++){
			List<Interaction> train = data.getTrainCVFold(numFolds, i).getInteractions();
			List<Interaction> test = data.getTestCVFold(numFolds, i).getInteractions();
			PrintWriter writer = null;
			try {
				writer = new PrintWriter(out+"/AIMedTrainKernel"+i);
				kernel.printTrain(writer, train);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}finally{
				writer.close();
			}
			try {
				writer = new PrintWriter(out+"/AIMedTestKernel"+i);
				kernel.printTest(writer,train,test);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}finally{
				writer.close();
			}
		}
	}
}
